<?php
if (!defined('ABSPATH')) {
    exit();
}
/**
 * Create response for datatable AJAX request
 */
function get_ajax_data()
{
    

    $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']) : '');

    if (!wp_verify_nonce($nonce, 'wp_rest')) {
        echo json_encode(array("draw" => 1, "recordsTotal" => 1, "recordsFiltered" => 1, "data" => [], 'error' => 'nonce_failed'));
        wp_die();
    }

    // Sanitize and initialize input variables
    $selecetd_category = isset($_POST['category']) ? esc_sql($_POST['category']) : '';
    $predi_val = isset($_POST['predi_val']) ? sanitize_text_field($_POST['predi_val']) : '';
    $predi_per = isset($_POST['predi_per']) ? sanitize_text_field($_POST['predi_per']) : '';
    $show_predi = isset($_POST['show_predi']) ? sanitize_text_field($_POST['show_predi']) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
    $start_point = isset($_POST['start']) ? intval(esc_sql($_POST['start'])) : 0;
    $current_page = isset($_POST['draw']) ? intval(esc_sql($_POST['draw'])) : 1;
    $fiat_currency = isset($_POST['currency']) ? sanitize_text_field($_POST['currency']) : 'USD';
    $fiat_currency_rate = isset($_POST['currencyRate']) ? floatval($_POST['currencyRate']) : 1.0;
    $total_coins = isset($_POST['totalCoins']) && is_numeric($_POST['totalCoins']) ? intval($_POST['totalCoins']) : -1;
    $fav_coins = isset($_POST['coinID']) ? esc_sql($_POST['coinID']) : 'NA';
    $data_length = isset($_POST['length']) ? intval(esc_sql($_POST['length'])) : 100;
    $coin_ids = array();

    if ($total_coins != -1 && $data_length > $total_coins) {
        $data_length = $total_coins;
    }

    // Adjust API data request based on start point
    if ($start_point > 2149) {
        CMC_api_data::cmc_get_selected_api_data(10);
    } elseif ($start_point > 1999) {
        CMC_api_data::cmc_get_selected_api_data(9);
    } elseif ($start_point > 1749) {
        CMC_api_data::cmc_get_selected_api_data(8);
    } elseif ($start_point > 1399) {
        CMC_api_data::cmc_get_selected_api_data(7);
    } elseif ($start_point > 1149) {
        CMC_api_data::cmc_get_selected_api_data(6);
    } elseif ($start_point > 899) {
        CMC_api_data::cmc_get_selected_api_data(5);
    } elseif ($start_point > 699) {
        CMC_api_data::cmc_get_selected_api_data(4);
    } elseif ($start_point > 399) {
        CMC_api_data::cmc_get_selected_api_data(3);
    } elseif ($start_point > 99) {
        CMC_api_data::cmc_get_selected_api_data(2);
    }

    $cmcDB = new CMC_Coins;
    $coins_list = array();
    $order_col_name = 'market_cap';
    $order_type = 'DESC';

    // Fetch coin data based on selected category and favorite coins
    if ($selecetd_category != 'all' && $fav_coins != 'NA') {
        $coindata = $cmcDB->get_coins(array(
            "coin_id" => $fav_coins,
            "coin_category" => $selecetd_category,
            "number" => $data_length,
            'offset' => $start_point,
            'orderby' => $order_col_name,
            'order' => $order_type,
            'coin_search' => strtoupper(esc_sql($_POST['search']))
        ));
    } elseif ($selecetd_category != 'all') {
        $coindata = $cmcDB->get_coins(array(
            "coin_category" => $selecetd_category,
            "number" => $data_length,
            'offset' => $start_point,
            'orderby' => $order_col_name,
            'order' => $order_type,
            'coin_search' => strtoupper(esc_sql($_POST['search']))
        ));
    } else {
        if ($fav_coins == 'NA') {
            $coindata = $cmcDB->get_coins(array(
                "number" => $data_length,
                'offset' => $start_point,
                'orderby' => $order_col_name,
                'order' => $order_type,
                'coin_search' => strtoupper(esc_sql($_POST['search']))
            ));
        } else {
            $coindata = $cmcDB->get_coins(array(
                "coin_id" => $fav_coins,
                "number" => $data_length,
                'offset' => $start_point,
                'orderby' => $order_col_name,
                'order' => $order_type
            ));
        }
    }


    if ($coindata) {
        foreach ($coindata as $coin) {
            $coin_ids[] = $coin->coin_id;
        }
    }

    $response = array();
    $coins = array();
    $bitcoin_price = 1;
    $coins_list = array();
    if ($coindata) {
        $i = $start_point + 1;
        $bitcoin_price = 1;
        foreach ($coindata as $coin) {
            $coin = (array) $coin;
            // Set stable coin cate variable for prediction(It is used when we change currency from front end side)
            $stable_coin_cate = false;

            $cate = ($coin['coin_category']) ? unserialize($coin['coin_category']) : '';

            if (is_array($cate) && $show_predi == 'yes') {

                if (in_array('stable-coin', $cate)) {
                    // var_dump($coin['price']);
                    $stable_coin_cate = true;
                }
            }

            $local_logo = coin_list_logo($coin['coin_id'], $size = 32);
            $coin_id = $coin['coin_id'];
            if ($coin_id == 'bitcoin') {
                $btc_price = $coin['price'];
            }
            $coins['logo'] = ($local_logo == false) ? CMC_COINS_LOGO . trim($coin['logo']) : $local_logo;
            $symbol = strtoupper($coin['symbol']);
            $coins['rank'] = $i;
            $coins['last_updated'] = $coin['last_updated'];
            $coins['coin_id'] = $coin['coin_id'];
            $coins['stable_coin_cate'] = $stable_coin_cate;
            $coins['watch_list'] = $coin['coin_id'];
            $coins['symbol'] = $symbol;
            $coins['name'] = strtoupper($coin['name']);
            $coins['usd_price'] = $coin['price'];
            $coins['usd_ath_price'] = $coin['ath'];
            $coins['usd_high_24h'] = $coin['high_24h'];
            $coins['usd_low_24h'] = $coin['low_24h'];
            $coins['usd_market_cap'] = $coin['market_cap'];
            $coins['usd_volume'] = $coin['total_volume'];
            $coins['rating'] = "";
            $coins['auditado'] = "";
            $coins['risco'] = 0;
            $coins['auditadoLogo'] = CMC_URL . 'images/aditado.svg';
            if (get_option('cmc_custom_desc_meta_data') != false) {
                $custom_des_data = get_option('cmc_custom_desc_meta_data');
                $coins['rating'] = isset($custom_des_data[$coin_id]['rating']) && !empty($custom_des_data[$coin_id]['rating']) ? $custom_des_data[$coin_id]['rating'] : "";
                $coins['risco'] = (int) $coins['rating'];
                $coins['auditado'] = isset($custom_des_data[$coin_id]['auditado']) && !empty($custom_des_data[$coin_id]['auditado']) ? $custom_des_data[$coin_id]['auditado'] : "";
            }
            if ($fiat_currency == "USD") {
                $coins['price'] = $coin['price'];
                $coins['market_cap'] = $coin['market_cap'];
                $coins['volume'] = $coin['total_volume'];
                $coins['ath'] = $coin['ath'];
                $coins['high_24h'] = $coin['high_24h'];
                $coins['low_24h'] = $coin['low_24h'];
                /**Prediction Code start*/
                $cate = ($coin['coin_category']) ? unserialize($coin['coin_category']) : '';
                if (has_action("cmc_prediction_data")) {
                    ob_start();
                    do_action('cmc_prediction_data', array('post_id' => $post_id, 'cate' => $cate, 'price' => $coin['price'], 'fiat_currency' => $fiat_currency));
                    $action_output = ob_get_contents();
                    ob_end_clean();
                    $coins['cmc_predi'] = $action_output;
                }
                /**Prediction Code End*/
                $c_price = $coin['price'];
            } else if ($fiat_currency == "BTC") {
                $coin_price = $coin['price'] / $bitcoin_price;
                $coins['price'] = $coin['price'] / $bitcoin_price;
                $coins['market_cap'] = $coin['market_cap'] / $bitcoin_price;
                $coins['volume'] = $coin['total_volume'] / $bitcoin_price;
                $coins['ath'] = $coin['ath'] / $bitcoin_price;
                $coins['high_24h'] = $coin['high_24h'] / $bitcoin_price;
                $coins['low_24h'] = $coin['low_24h'] / $bitcoin_price;
                /**Prediction Code start*/
                $cate = ($coin['coin_category']) ? unserialize($coin['coin_category']) : '';
                if (has_action("cmc_prediction_data")) {
                    ob_start();
                    do_action('cmc_prediction_data', array('post_id' => $post_id, 'cate' => $cate, 'price' => $coin_price, 'fiat_currency' => $fiat_currency));
                    $action_output = ob_get_contents();
                    ob_end_clean();
                    $coins['cmc_predi'] = $action_output;
                }
                /**Prediction Code End*/
            } else {
                $coin_price = $coin['price'] * $fiat_currency_rate;
                $coins['price'] = $coin['price'] * $fiat_currency_rate;
                $coins['market_cap'] = $coin['market_cap'] * $fiat_currency_rate;
                $coins['volume'] = $coin['total_volume'] * $fiat_currency_rate;
                $coins['ath'] = $coin['ath'] * $fiat_currency_rate;
                $coins['high_24h'] = $coin['high_24h'] * $fiat_currency_rate;
                $coins['low_24h'] = $coin['low_24h'] * $fiat_currency_rate;
                /**Prediction Code start*/
                $cate = ($coin['coin_category']) ? unserialize($coin['coin_category']) : '';
                if (has_action("cmc_prediction_data")) {
                    ob_start();
                    do_action('cmc_prediction_data', array('post_id' => $post_id, 'cate' => $cate, 'price' => $coin_price, 'fiat_currency' => $fiat_currency));
                    $action_output = ob_get_contents();
                    ob_end_clean();
                    $coins['cmc_predi'] = $action_output;
                }
                /**Prediction Code End*/
            }

            $coins['supply'] = $coin['circulating_supply'];
            $coins['percent_change_24h'] = number_format(is_numeric($coin['percent_change_24h']) ? $coin['percent_change_24h'] : 0, 2, '.', '');
            $coins['percent_change_7d']  = number_format(is_numeric($coin['percent_change_7d']) ? $coin['percent_change_7d'] : 0, 2, '.', '');
            $coins['percent_change_30d'] = number_format(is_numeric($coin['percent_change_30d']) ? $coin['percent_change_30d'] : 0, 2, '.', '');
            $coins['percent_change_1y']  = number_format(is_numeric($coin['percent_change_1y']) ? $coin['percent_change_1y'] : 0, 2, '.', '');
            $coins['ath_change_percentage'] = number_format(is_numeric($coin['ath_change_percentage']) ? $coin['ath_change_percentage'] : 0, 2, '.', '');
            $coins['ath_date'] = $coin['ath_date'];
            $coins['extradata'] = isset($coin['extradata']) ? maybe_unserialize($coin['extradata']) : "";

            if (isset($coin['weekly_price_data']) && $coin['weekly_price_data'] != 'N/A' && !empty($coin['weekly_price_data'])) {
                $chart = unserialize($coin['weekly_price_data']);
                if (is_array($chart)) {
                    array_push($chart, $coin['price']);
                    $coins['weekly_chart'] = json_encode($chart);
                } else {
                    $coin['weekly_chart'] = 'false';
                }
            } else {
                $coins['weekly_chart'] = 'false';
            }

            $i++;

            $coins_list[] = $coins;
            if ($total_coins != -1 && $i > $total_coins) {
                break;
            }
        }
    }
   
    $response = array(
        "draw" =>esc_html($current_page),
        "recordsTotal" => CMC_LOAD_COINS,
        "recordsFiltered" =>esc_html($total_coins == -1 ? CMC_LOAD_COINS:$total_coins), 
        "data" => $coins_list
        );
    echo json_encode($response);
    exit();
}
